package com.leetcode.fenzhi;

import java.util.Arrays;

/**
 * leetcode 1011 在D天内送达包裹的能力
 */
public class Solution1011 {
    public int shipWithinDays(int[] weights, int days) {
        if (weights == null || weights.length == 0) {
            return 0;
        }

        int left = Arrays.stream(weights).max().getAsInt();
        int right = Arrays.stream(weights).sum();
        int mid;
        while(left <= right) {
            mid = left + (right - left) / 2;
            if (needDays(weights, mid) == days) {
                right = mid - 1;
            } else if (needDays(weights, mid) < days) {
                right = mid - 1;
            } else {
                left = mid + 1;
            }
        }

        return right + 1;
    }

    private int needDays(int[] weights, int speed) {
        int result = 0;
        int sum = 0;
        for (int i = 0; i < weights.length; i++) {
            if (sum + weights[i] > speed) {
                result++;
                sum = weights[i];
            } else {
                sum += weights[i];
            }
        }
        result++;
        return result;
    }

    public static void main(String[] args) {
        Solution1011 solution1011 = new Solution1011();
        int[] test = new int[]{1, 2, 3, 1, 1};
        System.out.println(solution1011.shipWithinDays(test, 4));
    }
}
